package cn.campsg.messageboard.controller;

import cn.campsg.messageboard.dao.UserDao;
import cn.campsg.messageboard.model.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@WebServlet("/ProfileServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024, maxFileSize = 2 * 1024 * 1024, maxRequestSize = 5 * 1024 * 1024)
public class ProfileServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "avatars";
    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        
        if (username == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        // 获取用户信息
        User user = userDao.getUserByUsername(username);
        if (user != null) {
            request.setAttribute("user", user);
        }
        
        request.getRequestDispatcher("profile.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        
        if (username == null) {
            response.sendRedirect("login.jsp");
            return;
        }
        
        // 获取用户信息
        User user = userDao.getUserByUsername(username);
        if (user == null) {
            request.setAttribute("updateError", "用户信息获取失败");
            request.getRequestDispatcher("profile.jsp").forward(request, response);
            return;
        }
        
        // 处理表单数据
        String email = request.getParameter("email");
//        String signature = request.getParameter("signature");
        
        // 处理头像上传
        String avatarUrl = user.getAvatar(); // 默认为原有头像
        Part filePart = request.getPart("avatarFile"); // 获取上传的文件部分
        
        if (filePart != null && filePart.getSize() > 0) {
            try {
                avatarUrl = uploadAvatar(filePart, request);
            } catch (IOException e) {
                request.setAttribute("updateError", "头像上传失败：" + e.getMessage());
                request.getRequestDispatcher("profile.jsp").forward(request, response);
                return;
            }
        }
        
        // 更新用户信息
        user.setEmail(email);
//        user.setSignature(signature);
        user.setAvatar(avatarUrl);
        
        boolean updated = userDao.updateUser(user);
        
        if (updated) {
            session.setAttribute("username", user.getUsername()); // 确保session中的用户名是最新的
            session.setAttribute("user", user);
            request.setAttribute("updateSuccess", "个人信息更新成功");
        } else {
            request.setAttribute("updateError", "个人信息更新失败，请重试");
        }
        
        request.setAttribute("user", user);
        request.getRequestDispatcher("profile.jsp").forward(request, response);
    }
    
    private String uploadAvatar(Part filePart, HttpServletRequest request) throws IOException {
        // 构建上传目录
        String uploadPath = getServletContext().getRealPath("/") + UPLOAD_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + getFileName(filePart);
        Path filePath = Paths.get(uploadPath, fileName);
        
        // 保存文件
        try (InputStream fileContent = filePart.getInputStream()) {
            Files.copy(fileContent, filePath);
        }
        
        // 返回文件访问路径
        return request.getContextPath() + "/" + UPLOAD_DIR + "/" + fileName;
    }
    
    private String getFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] items = contentDisposition.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename")) {
                return item.substring(item.indexOf("=") + 2, item.length() - 1);
            }
        }
        return "";
    }
}